<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\lists\promotion;


use app\adminapi\lists\BaseAdminDataLists;
use app\adminapi\logic\auth\AdminLogic;
use app\common\model\callback\OrderCallback;
use app\common\model\order\Order;
use app\common\model\promotion\PromotionLink;
use app\common\lists\ListsSearchInterface;
use app\common\model\recycle_report\RecycleReport;
use function DI\string;


/**
 * PromotionLink列表
 * Class PromotionLinkLists
 * @package app\adminapi\lists
 */
class PromotionLinkLists extends BaseAdminDataLists implements ListsSearchInterface
{


    /**
     * @notes 设置搜索条件
     * @return \string[][]
     * @author likeadmin
     * @date 2024/03/04 19:26
     */
    public function setSearch(): array
    {
        return [
            '%like%' => ['book_name', 'name'],
            '='      => ['platform', 'id', 'media', 'add_desktop_type', 'status'],
        ];
    }


    /**
     * @notes 获取列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author likeadmin
     * @date 2024/03/04 19:26
     */
    public function lists(): array
    {
        $list = PromotionLink::where($this->searchWhere)->where($this->queryWhere())
            ->field(['id', 'platform', 'admin_id', 'media', 'name', 'book_id', 'book_name', 'bookpack_type', 'remark', 'add_desktop_type', 'paytype', 'egold', 'status', 'add_fans', 'add_desktop_user'])
            ->append(['pay_chapter', 'advertiser_name', 'links_switch'])
            ->limit($this->limitOffset, $this->limitLength)
            ->order(['id' => 'desc'])
            ->select()
            ->toArray();
        foreach ($list as &$item) {
            $date              = date('Y-m-d');
            $promotion_link_id = $item['id'];
            $all_recharge_num  = OrderCallback::where(['recharge_times' => 1, 'promotion_link_id' => $promotion_link_id])->count();

            $promotionLinkReport = RecycleReport::where(['count_date' => $date, 'promotion_link_id' => $promotion_link_id])->findOrEmpty();
            $all_recharge_money  = Order::with([
                'callback' => function ($q) {
                    $q->withField('id,order_id,promotion_link_id');
                },
            ])->hasWhere('callback', function ($query) use ($promotion_link_id) {
                $query->where('promotion_link_id', '=', $promotion_link_id);
            })->sum('money');
            if (!$promotionLinkReport->isEmpty()) {
                $item['new_fans_num']          = $promotionLinkReport->new_fans_num;//当日粉丝数
                $item['add_desktop_num']       = $promotionLinkReport->add_desktop_num;//当日加桌
                $item['new_fans_pay_num']      = $promotionLinkReport->new_fans_pay_num;//新用户充值数
                $item['add_up_recharge_money'] = $promotionLinkReport->add_up_recharge_money;//新用户充值金额
            } else {
                $item['new_fans_num']          = 0;
                $item['add_desktop_num']       = 0;
                $item['new_fans_pay_num']      = 0;
                $item['add_up_recharge_money'] = 0;
            }
            $item['all_recharge_money'] = $all_recharge_money;//累计充值金额
            if ($all_recharge_num > 0) {
                $two_recharge_num                = OrderCallback::where(['recharge_times' => 2, 'promotion_link_id' => $promotion_link_id])->count();
                $three_recharge_num              = OrderCallback::where(['recharge_times' => 3, 'promotion_link_id' => $promotion_link_id])->count();
                $four_recharge_num               = OrderCallback::where(['recharge_times' => 4, 'promotion_link_id' => $promotion_link_id])->count();
                $five_recharge_num               = OrderCallback::where(['recharge_times' => 5, 'promotion_link_id' => $promotion_link_id])->count();
                $item['secondary_charging_rate'] = strval(bcdiv($two_recharge_num, $all_recharge_num, 4) * 100) . '%';//二充率
                $item['triple_charge_rate']      = strval(bcdiv($three_recharge_num, $all_recharge_num, 4) * 100) . '%';//三充率
                $item['four_charge_rate']        = strval(bcdiv($four_recharge_num, $all_recharge_num, 4) * 100) . '%';//四充率
                $item['five_charge_rate']        = strval(bcdiv($five_recharge_num, $all_recharge_num, 4) * 100) . '%';//五充率
            } else {
                $item['secondary_charging_rate'] = '-';//二充率
                $item['triple_charge_rate']      = '-';//三充率
                $item['four_charge_rate']        = '-';//四充率
                $item['five_charge_rate']        = '-';//五充率
            }
        }

        return $list;
    }

    /**
     * @notes 搜索条件
     * @author 段誉
     * @date 2023/2/24 16:08
     */
    public function queryWhere()
    {
        $where = [];
        // TODO 管理员权限控制
        if ($this->params['platform'] != 6) {
            if ($this->adminInfo['root'] != 1) {
                $pAdminIds = AdminLogic::getPermissionAdminIds($this->adminInfo);
                $where[]   = ['admin_id', 'in', $pAdminIds];
            }
        }

        return $where;
    }


    /**
     * @notes 获取数量
     * @return int
     * @author likeadmin
     * @date 2024/03/04 19:26
     */
    public function count(): int
    {
        return PromotionLink::where($this->searchWhere)->where($this->queryWhere())->count();
    }

}
